package com.xmb.wechat.picasso;

import android.graphics.Bitmap;

import com.squareup.picasso.Transformation;

/**
 * 压缩图片，让图片加载更快
 */
public class PicassoSizeFitTransform implements Transformation {
    private int targetMaxWidth;

    public PicassoSizeFitTransform(int targetMaxWidth) {
        this.targetMaxWidth = targetMaxWidth;
    }

    @Override
    public Bitmap transform(Bitmap source) {
        //返回原图
        if (source.getWidth() == 0 || source.getWidth() < targetMaxWidth) {
            return source;
        }
        //缩放
        int targetWidth;
        int targetHeight;
        double aspectRatio = (double) source.getHeight() / (double) source.getWidth();//原图的宽高比
        if (aspectRatio >= 2) {//竖图 (高是宽的两倍)
            targetWidth = targetMaxWidth / 2;
        } else if (aspectRatio > 1 && aspectRatio < 2) {//竖图
            targetWidth = (int) (targetMaxWidth * 0.44f * aspectRatio);
        } else if (aspectRatio == 1) {//正方形
            targetWidth = targetMaxWidth;
        } else if (aspectRatio > 0.5 && aspectRatio < 1) {//横图
            targetWidth = (int) (targetMaxWidth * 1f);
        } else {//横图(宽是高的两倍之上)
            targetWidth = (int) (targetMaxWidth * 1.25f);
        }
        targetHeight = (int) (targetWidth * aspectRatio);
        //结果
        Bitmap result = Bitmap.createScaledBitmap(source, targetWidth, targetHeight, false);
        if (result != source)
            source.recycle();
        return result;
    }

    @Override
    public String key() {
        return "transformation" + " desiredWidth";
    }
}
